package com.yan.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yan.edu.entity.Subject;
import com.yan.edu.entity.excel.SubjectData;
import com.yan.edu.entity.subject.OneSubject;
import com.yan.edu.entity.subject.TwoSubject;
import com.yan.edu.listener.SubjectExcelListener;
import com.yan.edu.mapper.SubjectMapper;
import com.yan.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-09-17
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file,SubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getOneTwoSubject() {
//        1、查询所有以及分类
        QueryWrapper<Subject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id",0);
        List<Subject> oneSubjects = baseMapper.selectList(wrapperOne);
//        2、查询所有二级分类
        QueryWrapper<Subject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id",0);
        List<Subject> twoSubjects = baseMapper.selectList(wrapperTwo);

//创建List集合，用于储存封装最终数据
        List<OneSubject> finalSubjectList=new ArrayList<>();

//        封装一级分类

        for (int i = 0; i < oneSubjects.size(); i++) {
            Subject eduSubject = oneSubjects.get(i);
            OneSubject oneSubject = new OneSubject();
//            oneSubject.setId(eduSubject.getId());
//            oneSubject.setTitle(eduSubject.getTitle());
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSubjectList.add(oneSubject);

//            在一级分类的循环中遍历查询所有的二级分类
            List<TwoSubject> twoFinalSubjectList=new ArrayList<>();
            for (int i1 = 0; i1 < twoSubjects.size(); i1++) {
                Subject tSubject = twoSubjects.get(i1);
                if(tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    twoFinalSubjectList.add(twoSubject);

                }


            }
            oneSubject.setChildren(twoFinalSubjectList);


        }

//        封装二级分类

        return finalSubjectList;
    }
}
